<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kylin</title><meta name="keywords" content="学习，博客，技术交流，学习记录，Kylin，kylin"><meta name="author" content="Kylin"><meta name="copyright" content="Kylin"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="学习不易，努力努力~">
<meta property="og:type" content="website">
<meta property="og:title" content="Kylin">
<meta property="og:url" content="https://www.codekylin.cn/page/13/index.html">
<meta property="og:site_name" content="Kylin">
<meta property="og:description" content="学习不易，努力努力~">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://qiniu.codekylin.cn/img/20200807181526.jpg">
<meta property="article:author" content="Kylin">
<meta property="article:tag" content="学习，博客，技术交流，学习记录，Kylin，kylin">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://qiniu.codekylin.cn/img/20200807181526.jpg"><link rel="shortcut icon" href="https://qiniu.codekylin.cn/img/20200807181548.png"><link rel="canonical" href="https://www.codekylin.cn/page/13/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.google-analytics.com" crossorigin=""/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><meta name="google-site-verification" content="gzeyWstt6NoTZKh7YFYNLNziL8HIZ8YH2Ug7xTDX5-Y"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?f76c34daefe747deee7c7be3ead2ba80";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script async="async" src="https://www.googletagmanager.com/gtag/js?id=UA-159334016-1"></script><script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-159334016-1');
</script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: {"limitDay":90,"position":"top","messagePrev":"自上次更新以来已经","messageNext":"天，文章的内容可能已过时或存在差异。"},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50000,"languages":{"author":"作者: Kylin","link":"链接: ","source":"来源: Kylin","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#FF0000","bgDark":"#2d3035","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: false,
  isHome: true,
  isHighlightShrink: false,
  isToc: false,
  postUpdate: '2022-10-12 21:14:27'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
          const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
          const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
          const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified

          if (t === undefined) {
            if (isLightMode) activateLightMode()
            else if (isDarkMode) activateDarkMode()
            else if (isNotSpecified || hasNoSupport) {
              const now = new Date()
              const hour = now.getHours()
              const isNight = hour <= 6 || hour >= 18
              isNight ? activateDarkMode() : activateLightMode()
            }
            window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
              if (saveToLocal.get('theme') === undefined) {
                e.matches ? activateDarkMode() : activateLightMode()
              }
            })
          } else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><link rel="stylesheet" href="https://qiniu.codekylin.cn/github/img/img/custom.css"><link rel="stylesheet" href="//at.alicdn.com/t/font_1993646_z05rabxf05h.css"><link rel="stylesheet" href="https://qiniu.codekylin.cn/github/img/img/icon.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Kylin" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" data-lazy-src="https://qiniu.codekylin.cn/img/20200807181526.jpg" onerror="onerror=null;src='https://qiniu.codekylin.cn/github/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">362</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">427</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">101</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="page" id="body-wrap"><header class="full_page" id="page-header" style="background-image: url('https://qiniu.codekylin.cn/github/img/img20201017211426.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Kylin</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="site-info"><h1 id="site-title">Kylin</h1><div id="site-subtitle"><span id="subtitle"></span></div><div id="site_social_icons"><a class="social-icon" href="https://github.com/kylincw" target="_blank" title="Github"><i class="iconfont icon-github"></i></a><a class="social-icon" href="tencent://message/?Menu=yes&amp;uin=171346168&amp;Service=300&amp;sigT=45a1e5847943b64c6ff3990f8a9e644d2b31356cb0b4ac6b24663a3c8dd0f8aa12a595b1714f9d45" target="_blank" title="qq"><i class="iconfont icon-qq"></i></a><a class="social-icon" href="https://space.bilibili.com/53836035" target="_blank" title="BiliBili"><i class="iconfont icon-bilibili-line"></i></a><a class="social-icon" href="mailto:zhang171346168@qq.com" target="_blank" title="Email"><i class="iconfont icon-email1"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS"><i class="iconfont icon-rss"></i></a></div></div><div id="scroll-down"><i class="fas fa-angle-down scroll-down-effects"></i></div></header><main class="layout" id="content-inner"><div class="recent-posts" id="recent-posts"><div class="recent-post-item"><div class="post_cover left_radius"><a href="/57539.html" title="JUC之自旋锁">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-nekg9l.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JUC之自旋锁"></a></div><div class="recent-post-info"><a class="article-title" href="/57539.html" title="JUC之自旋锁">JUC之自旋锁</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2020-09-26T07:42:51.000Z" title="发表于 2020-09-26 15:42:51">2020-09-26</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/Java/">Java</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/Java/JUC/">JUC</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/57539.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/57539.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">自旋锁是指尝试获取锁的线程不会立即阻塞，而是采用循环的方式去尝试获取锁，这样的好吃是减少线程上下文切换的消耗，缺点是循环会消耗CPU。
自旋的方式我们在查看AtomicInteger的底层时候就已经体验过了

123456789public final int getAndAddInt(Object var1, long var2, int var4) &#123;    int var5;    do &#123;        var5 = this.getIntVolatile(var1, var2);      //自旋    &#125; while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));    return var5;&#125;

手写自旋锁首先原子引用线程类AtomicReference&lt;Thread&gt; atomicReference = new AtomicReference&lt;&gt;();
接着编写myLock()首先通过Thread.currentThread();获取到当 ...</div></div></div><div class="recent-post-item"><div class="post_cover right_radius"><a href="/51393.html" title="JUC之可重入锁">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/images/20200601091329.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JUC之可重入锁"></a></div><div class="recent-post-info"><a class="article-title" href="/51393.html" title="JUC之可重入锁">JUC之可重入锁</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2020-09-26T06:59:51.000Z" title="发表于 2020-09-26 14:59:51">2020-09-26</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/51393.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/51393.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">可重入锁可重入锁又叫递归锁，指的是同一线程外层函数获得锁之后，内存递归函数仍然能获取该锁的代码，同一个线程在外层获取锁的时候，进入内层方法会自动获取锁。也就是说，线程可以进入任何一个它已经拥有的锁所同步者的代码块。
ReentrantLock/synchronized就是一个典型的可重入锁
代码验证synchronized
123456789101112131415161718192021222324public class ReenterLockDemo &#123;    public static void main(String[] args) &#123;        Phone phone = new Phone();        new Thread(() -&gt; &#123;            phone.sendSMS();        &#125;, &quot;t1&quot;).start();        new Thread(() -&gt; &#123;            phone.sendSMS();        &#125;,  ...</div></div></div><div class="recent-post-item"><div class="post_cover left_radius"><a href="/47426.html" title="JUC之公平锁和非公平锁">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-3kp6yv.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JUC之公平锁和非公平锁"></a></div><div class="recent-post-info"><a class="article-title" href="/47426.html" title="JUC之公平锁和非公平锁">JUC之公平锁和非公平锁</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2020-09-26T06:34:44.000Z" title="发表于 2020-09-26 14:34:44">2020-09-26</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/Java/">Java</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/Java/JUC/">JUC</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/47426.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/47426.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">概念公平锁是指多个线程按照申请锁的顺序来获取锁，采用先来后到哦，先来先服务的原则。老的线程排队使用锁，新线程仍然排队使用锁。
非公平锁多个线程按照上来就直接尝试占有锁，如果尝试失败就采用类似公平锁的方式。老的线程排队使用锁，但是无法保证新线程抢占已经在排队的线程的锁。
非公平锁的优点在于吞吐量比公平锁大。
并发包ReentrantLock的创建可以指定构造函数的boolean类型来得到公平锁或者非公平锁 默认是非公平锁
实例我们经常使用到的锁是ReentrantLock我们可以查看它的源码，默认使用的是非公平锁。


也就是说ReentrantLock可自定义使用的是公平还是非公平锁，默认使用的是非公平锁。
对于synchronized而言 也是一种非公平锁.
</div></div></div><div class="recent-post-item"><div class="post_cover right_radius"><a href="/20251.html" title="JUC之ABA问题">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/荒鲸.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JUC之ABA问题"></a></div><div class="recent-post-info"><a class="article-title" href="/20251.html" title="JUC之ABA问题">JUC之ABA问题</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2020-09-26T02:45:15.000Z" title="发表于 2020-09-26 10:45:15">2020-09-26</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/Java/">Java</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/Java/JUC/">JUC</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/20251.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/20251.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">什么是ABA问题？ABA问题是由CAS而导致的一个问题
CAS算法实现一个重要前提需要取出内存中某时刻的数据并在当下时刻比较并交换，那么在这个时间差内会导致数据的变化。
比如说一个线程一从内存位置V中取出A，这是另一个线程二也从内存中取出A，并且线程二进行类一些操作将值变成了B，然后线程二又将V位置的数据变成A，这时候线程一进行CAS操作发现内存中仍然是A，然后线程一操作成功！
尽管线程一的CAS操作成功，但是不代表这个过程就是没有问题的。

就比如你家每天，都有一个B流浪汉来你家进行生活，他每天在你回家的时候将家整理成你离开的样子，不留下痕迹。你每天回到家后没有发现什么异常于是就正常生活。虽然他目前没有对你的生活造成什么问题，但是这个过程是很有隐患的！！！
总的来说以前的CAS操作，只管过程，也就是开头和结尾是否相同，如果相同就进行操作！而不管你中间到底进行来什么操作！！
原子引用如何解决ABA问题呢？首先我们看一下原子引用。我们先前已经使用过java.util.concurrent.atomic下的基本数据类型原子操作类。但是缺少对对象的操作的原子类。也就是AtomicRefere ...</div></div></div><div class="recent-post-item"><div class="post_cover left_radius"><a href="/25239.html" title="JUC之CAS原理">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/博客封面14.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JUC之CAS原理"></a></div><div class="recent-post-info"><a class="article-title" href="/25239.html" title="JUC之CAS原理">JUC之CAS原理</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2020-09-26T01:03:32.000Z" title="发表于 2020-09-26 09:03:32">2020-09-26</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/Java/">Java</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/Java/JUC/">JUC</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/25239.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/25239.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">CAS概念CAS的英文为Compare and Swap 翻译为比较并交换。
CAS机制中使用了3个基本操作数：内存地址V，旧的预期值A，要修改的新值B。
更新一个变量的时候，只有当变量的预期值A和内存地址V当中的实际值相同时，才会将内存地址V对应的值修改为B。
CAS的全称为Compare-And-Swap ,它是一条CPU并发原语. 
它的功能是判断内存某个位置的值是否为预期值,如果是则更新为新的值,这个过程是原子的.
CAS并发原语提现在Java语言中就是sun.miscUnSaffe类中的各个方法.调用UnSafe类中的CAS方法,JVM会帮我实现CAS汇编指令 .这是一种完全依赖于硬件  功能,通过它实现了原子操作,再次强调,由于CAS是一种系统原语,原语属于操作系统用于范畴,是由若干条指令组成,用于完成某个功能的一个过程,并且原语的执行必须是连续的,在执行过程中不允许中断,也即是说CAS是一条原子指令,不会造成所谓的数据不一致的问题. 
CAS应用将CAS的应用前我们要先将一个类，这个类我们已经使用过了，就是下图这个例子。

123456789101112131415161 ...</div></div></div><div class="recent-post-item"><div class="post_cover right_radius"><a href="/57468.html" title="JUC之volatile详解">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/images/20200701211402.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JUC之volatile详解"></a></div><div class="recent-post-info"><a class="article-title" href="/57468.html" title="JUC之volatile详解">JUC之volatile详解</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2020-09-25T06:58:10.000Z" title="发表于 2020-09-25 14:58:10">2020-09-25</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/Java/">Java</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/Java/JUC/">JUC</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/57468.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/57468.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">volatilevolatile是Java虚拟机提供的轻量级的同步机制，保证可见性，不保证原子性，禁止指令重排（保证可序性）
Java内存模型JMM
验证可见性
12345678910111213141516171819202122232425262728293031323334353637public class VolatileDemo &#123;    public static void main(String[] args) &#123;        //volatile 可以保证可见性，及时通知其他线程，主物理内存的值已经被修改        MyData myData = new MyData();        new Thread(() -&gt; &#123;            System.out.println(Thread.currentThread().getName() + &quot;\t come in&quot;);            //暂停            try &#123;                //确保后面的mai ...</div></div></div><div class="recent-post-item"><div class="post_cover left_radius"><a href="/64150.html" title="Java内存模型JMM">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/博客封面20.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java内存模型JMM"></a></div><div class="recent-post-info"><a class="article-title" href="/64150.html" title="Java内存模型JMM">Java内存模型JMM</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2020-09-25T06:08:40.000Z" title="发表于 2020-09-25 14:08:40">2020-09-25</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/Java/">Java</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/Java/JUC/">JUC</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/64150.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/64150.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">Java内存模型概述Java内存模型(即Java Memory Model，简称JMM)本身是一种抽象的概念，并不真实存在，它描述的是一组规则或规范，通过这组规范定义了程序中各个变量（包括实例字段，静态字段和构成数组对象的元素）的访问方式。
由于JVM运行程序的实体是线程，而每个线程创建时JVM都会为其创建一个工作内存(有些地方称为栈空间)，用于存储线程私有的数据，而Java内存模型中规定所有变量都存储在主内存，主内存是共享内存区域，所有线程都可以访问，但线程对变量的操作(读取赋值等)必须在工作内存中进行，首先要将变量从主内存拷贝的自己的工作内存空间，然后对变量进行操作，操作完成后再将变量写回主内存，不能直接操作主内存中的变量，工作内存中存储着主内存中的变量副本拷贝，前面说过，工作内存是每个线程的私有数据区域，因此不同的线程间无法访问对方的工作内存，线程间的通信(传值)必须通过主内存来完成，其简要访问过程如下图


主内存
主要存储的是Java实例对象，所有线程创建的实例对象都存放在主内存中，不管该实例对象是成员变量还是方法中的本地变量(也称局部变量)，当然也包括了共享的类信息、常量、 ...</div></div></div><div class="recent-post-item"><div class="post_cover right_radius"><a href="/60919.html" title="JUC之集合类不安全">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/img/20200423185957.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JUC之集合类不安全"></a></div><div class="recent-post-info"><a class="article-title" href="/60919.html" title="JUC之集合类不安全">JUC之集合类不安全</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2020-09-25T00:53:19.000Z" title="发表于 2020-09-25 08:53:19">2020-09-25</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/Java/">Java</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/Java/JUC/">JUC</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/60919.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/60919.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">ArrayList首先手写一个案例来证明ArrayList不安全。

运行多次查看结果～

打印结果与我们的预期不符，list集合中添加了null。
将线程数量添加至30个

运行报java.util.ConcurrentModificationException并发修改异常

至此我们可以发现ArrayList是多线程下的不安全的。
123456789101112131415161718public class ContainerNotSafeDemo &#123;        public static void main(String[] args) &#123;        //java.util.ConcurrentModificationException        //new Vector&lt;&gt;();        //Collections.synchronizedList(new ArrayList&lt;&gt;());        //new CopyOnWriteArrayList&lt;&gt;();        List&lt;Stri ...</div></div></div><div class="recent-post-item"><div class="post_cover left_radius"><a href="/23872.html" title="JUC之八锁问题">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-mdz9x9.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JUC之八锁问题"></a></div><div class="recent-post-info"><a class="article-title" href="/23872.html" title="JUC之八锁问题">JUC之八锁问题</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2020-09-24T12:52:54.000Z" title="发表于 2020-09-24 20:52:54">2020-09-24</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/Java/">Java</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/Java/JUC/">JUC</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/23872.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/23872.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">环境准备首先编写一个MyPhone类，编写两个同步方法sendEmail和sendEMS方法

接着在Lock8类中的main方法中，创建两个A，B线程分别调用sendEmail和sendEMS方法。由于线程创建后是有CPU调度执行的，所以A，B线程执行顺序是随机的。为了测试效果，我们让主线程睡眠200毫米，从而确保每次执行顺序都是A线程先开始调度执行。

多次运行查看效果～，结果与预期相符。

12345678910111213141516171819202122232425262728293031323334353637public class Lock8 &#123;    public static void main(String[] args) throws InterruptedException &#123;        MyPhone phone = new MyPhone();        new Thread(() -&gt; &#123;            try &#123;                phone.sendEmail();      ...</div></div></div><div class="recent-post-item"><div class="post_cover right_radius"><a href="/28239.html" title="JUC之synchronized和Lock">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-od5gj7.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JUC之synchronized和Lock"></a></div><div class="recent-post-info"><a class="article-title" href="/28239.html" title="JUC之synchronized和Lock">JUC之synchronized和Lock</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2020-09-24T03:21:35.000Z" title="发表于 2020-09-24 11:21:35">2020-09-24</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/Java/">Java</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/Java/JUC/">JUC</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/28239.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/28239.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">为了解决线程同步问题我们经常使用synchronized关键字和Lock接口下的锁来解决同步问题。但是这两者有什么区别之处呢？首先我们分别使用synchronized和Lock来解决生产者消费者问题。
生产者消费者问题当生产者生产数量为1的时候，通知消费者消费。当生产者产品数量为0的时候，生产产品。
synchronized

运行测试，结果符合预期！

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081/** * 线程之间的通信问题：生产者和消费者问题！等待唤醒，通知唤醒 * 线程交替执行 A B 操作同一个变量 num = 0 * A num+1 * B num-1 */public class A &#123;    public static void main(String[] args) &#123;        Dat ...</div></div></div><nav id="pagination"><div class="pagination"><a class="extend prev" rel="prev" href="/page/12/#content-inner"><i class="fas fa-chevron-left fa-fw"></i></a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/12/#content-inner">12</a><span class="page-number current">13</span><a class="page-number" href="/page/14/#content-inner">14</a><span class="space">&hellip;</span><a class="page-number" href="/page/37/#content-inner">37</a><a class="extend next" rel="next" href="/page/14/#content-inner"><i class="fas fa-chevron-right fa-fw"></i></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" data-lazy-src="https://qiniu.codekylin.cn/img/20200807181526.jpg" onerror="this.onerror=null;this.src='https://qiniu.codekylin.cn/github/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">Kylin</div><div class="author-info__description">学习不易，努力努力~</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">362</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">427</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">101</div></a></div></div><a class="button--animated" id="card-info-btn"><i class="fas fa-bookmark"></i><span>加入书签</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/kylincw" target="_blank" title="Github"><i class="iconfont icon-github"></i></a><a class="social-icon" href="tencent://message/?Menu=yes&amp;uin=171346168&amp;Service=300&amp;sigT=45a1e5847943b64c6ff3990f8a9e644d2b31356cb0b4ac6b24663a3c8dd0f8aa12a595b1714f9d45" target="_blank" title="qq"><i class="iconfont icon-qq"></i></a><a class="social-icon" href="https://space.bilibili.com/53836035" target="_blank" title="BiliBili"><i class="iconfont icon-bilibili-line"></i></a><a class="social-icon" href="mailto:zhang171346168@qq.com" target="_blank" title="Email"><i class="iconfont icon-email1"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS"><i class="iconfont icon-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">学习不易，努力努力！</div></div><div class="sticky_layout"><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/56352.html" title="be动词"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/博客封面10.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="be动词"/></a><div class="content"><a class="title" href="/56352.html" title="be动词">be动词</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/36436.html" title="JVM堆内存"><img data-lazy-src="https://qiniu.codekylin.cn/img/20200418115059.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JVM堆内存"/></a><div class="content"><a class="title" href="/36436.html" title="JVM堆内存">JVM堆内存</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/44292.html" title="Java多线程详解"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-eorjzk.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java多线程详解"/></a><div class="content"><a class="title" href="/44292.html" title="Java多线程详解">Java多线程详解</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/40200.html" title="谷粒商城记录"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-6qvvrx.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="谷粒商城记录"/></a><div class="content"><a class="title" href="/40200.html" title="谷粒商城记录">谷粒商城记录</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/27082.html" title="Spring学习-3"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-4x28xo.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Spring学习-3"/></a><div class="content"><a class="title" href="/27082.html" title="Spring学习-3">Spring学习-3</a><time datetime="2022-07-12T11:47:29.799Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div></div></div><div class="card-widget" id="card-newest-comments"><div class="item-headline"><i class="fas fa-bolt"></i><span>最新评论</span></div><div class="aside-list"><span>正在加载中...</span></div></div><div class="card-widget card-categories"><div class="item-headline">
            <i class="fas fa-folder-open"></i>
            <span>分类</span>
            <a class="card-more-btn" href="/categories/" title="查看更多">
    <i class="fas fa-angle-right"></i></a>
            </div>
            <ul class="card-category-list" id="aside-cat-list">
            <li class="card-category-list-item parent"><a class="card-category-list-link" href="/categories/Docker/"><span class="card-category-list-name">Docker</span><span class="card-category-list-count">8</span><i class="fas fa-caret-left "></i></a><ul class="card-category-list child"><li class="card-category-list-item "><a class="card-category-list-link" href="/categories/Docker/CIG/"><span class="card-category-list-name">CIG</span><span class="card-category-list-count">1</span></a></li><li class="card-category-list-item "><a class="card-category-list-link" href="/categories/Docker/compose/"><span class="card-category-list-name">compose</span><span class="card-category-list-count">1</span></a></li></ul></li><li class="card-category-list-item "><a class="card-category-list-link" href="/categories/Elasticsearch/"><span class="card-category-list-name">Elasticsearch</span><span class="card-category-list-count">5</span></a></li><li class="card-category-list-item "><a class="card-category-list-link" href="/categories/English/"><span class="card-category-list-name">English</span><span class="card-category-list-count">1</span></a></li><li class="card-category-list-item parent"><a class="card-category-list-link" href="/categories/Java/"><span class="card-category-list-name">Java</span><span class="card-category-list-count">69</span><i class="fas fa-caret-left "></i></a><ul class="card-category-list child"><li class="card-category-list-item "><a class="card-category-list-link" href="/categories/Java/IO%E6%B5%81/"><span class="card-category-list-name">IO流</span><span class="card-category-list-count">10</span></a></li><li class="card-category-list-item "><a class="card-category-list-link" href="/categories/Java/JDBC/"><span class="card-category-list-name">JDBC</span><span class="card-category-list-count">5</span></a></li></ul></li>
            </ul></div><div class="card-widget card-tags"><div class="item-headline"><i class="fas fa-tags"></i><span>标签</span></div><div class="card-tag-cloud"><a href="/tags/ajax/" style="font-size: 1.15em; color: rgb(29, 46, 14)">ajax</a><a href="/tags/SpringBoot/" style="font-size: 1.45em; color: rgb(40, 91, 26)">SpringBoot</a><a href="/tags/Docker/" style="font-size: 1.3em; color: rgb(68, 166, 82)">Docker</a><a href="/tags/Dockerfile/" style="font-size: 1.15em; color: rgb(1, 93, 85)">Dockerfile</a><a href="/tags/%E5%AE%89%E8%A3%85/" style="font-size: 1.15em; color: rgb(194, 55, 83)">安装</a><a href="/tags/%E5%8D%B8%E8%BD%BD/" style="font-size: 1.15em; color: rgb(43, 190, 86)">卸载</a><a href="/tags/Docker%E7%9A%84%E4%BD%BF%E7%94%A8/" style="font-size: 1.15em; color: rgb(98, 192, 42)">Docker的使用</a><a href="/tags/Portainer/" style="font-size: 1.15em; color: rgb(180, 104, 53)">Portainer</a><a href="/tags/ES6/" style="font-size: 1.15em; color: rgb(185, 98, 89)">ES6</a><a href="/tags/%E7%AE%AD%E5%A4%B4%E5%87%BD%E6%95%B0/" style="font-size: 1.15em; color: rgb(135, 130, 156)">箭头函数</a></div></div><div class="card-widget card-archives"><div class="item-headline"><i class="fas fa-archive"></i><span>归档</span><a class="card-more-btn" href="/archives/" title="查看更多">
    <i class="fas fa-angle-right"></i></a></div><ul class="card-archive-list"><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2022/03/"><span class="card-archive-list-date">2022年03月</span><span class="card-archive-list-count">4</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2022/02/"><span class="card-archive-list-date">2022年02月</span><span class="card-archive-list-count">4</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2022/01/"><span class="card-archive-list-date">2022年01月</span><span class="card-archive-list-count">11</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/12/"><span class="card-archive-list-date">2021年12月</span><span class="card-archive-list-count">4</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/11/"><span class="card-archive-list-date">2021年11月</span><span class="card-archive-list-count">3</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/06/"><span class="card-archive-list-date">2021年06月</span><span class="card-archive-list-count">5</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/05/"><span class="card-archive-list-date">2021年05月</span><span class="card-archive-list-count">2</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/03/"><span class="card-archive-list-date">2021年03月</span><span class="card-archive-list-count">4</span></a></li></ul></div><div class="card-widget card-webinfo"><div class="item-headline"><i class="fas fa-chart-line"></i><span>网站资讯</span></div><div class="webinfo"><div class="webinfo-item"><div class="item-name">文章数目 :</div><div class="item-count">362</div></div><div class="webinfo-item"><div class="item-name">已运行时间 :</div><div class="item-count" id="runtimeshow" data-publishDate="2019-08-01T16:00:00.000Z"></div></div><div class="webinfo-item"><div class="item-name">本站总字数 :</div><div class="item-count">539.1k</div></div><div class="webinfo-item"><div class="item-name">最后更新时间 :</div><div class="item-count" id="last-push-date" data-lastPushDate="2022-10-12T13:14:25.092Z"></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://qiniu.codekylin.cn/github/img/img20201017211426.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2022 By Kylin</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/"><img class="icp-icon" src="https://img.alicdn.com/tfs/TB1..50QpXXXXX7XpXXXXXXXXXX-40-40.png"><span>湘ICP备2022005420号-1</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>(() => {
  function loadValine () {
    function initValine () {
      let initData = {
        el: '#vcomment',
        appId: 'ClIyIUhj1ue2rcRTsApYCR50-gzGzoHsz',
        appKey: 'ATug9IScYQBHILhKWEqBHYxM',
      }
      
      const valine = new Valine(initData)
    }

    if (typeof Valine === 'function') initValine() 
    else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
  }

  window.pjax ? loadValine() : window.addEventListener('load', loadValine)
})()</script><script>function subtitleType () {
  getScript('https://sdk.jinrishici.com/v2/browser/jinrishici.js').then(() => {
    jinrishici.load(function (result) {
      if (true) {
        var sub = "今日事&#44;今日畢,Never put off till tomorrow what you can do today".length == 0 ? new Array() : "今日事&#44;今日畢,Never put off till tomorrow what you can do today".split(',')
        var content = result.data.content
        var both = sub.unshift(content)
        var typed = new Typed('#subtitle', {
          strings: sub,
          startDelay: 300,
          typeSpeed: 150,
          loop: true,
          backSpeed: 50,
        })
      } else {
        document.getElementById('subtitle').innerHTML = result.data.content
      }
    })
  })
}

if (true) {
  if (typeof Typed === 'function') {
    subtitleType()
  } else {
    getScript('https://cdn.jsdelivr.net/npm/typed.js/lib/typed.min.js').then(subtitleType)
  }
} else {
  subtitleType()
}
</script></div><script src="https://cdn.jsdelivr.net/npm/blueimp-md5@2.17.0/js/md5.min.js"></script><script>window.addEventListener('load', () => {
  const changeContent = (content) => {
    if (content === '') return content

    content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[图片]') // replace image link
    content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[链接]') // replace url
    content = content.replace(/<pre><code>.*?<\/pre>/gi, '[代码]') // replace code
    content = content.replace(/<[^>]+>/g,"") // remove html tag

    if (content.length > 150) {
      content = content.substring(0,150) + '...'
    }
    return content
  }

  const getIcon = (icon, mail) => {
    if (icon) return icon
    let defaultIcon = '?d=robohash'
    let iconUrl = `https://gravatar.loli.net/avatar/${md5(mail.toLowerCase()) + defaultIcon}`
    return iconUrl
  }

  const generateHtml = array => {
    let result = ''

    if (array.length) {
      for (let i = 0; i < array.length; i++) {
        result += '<div class=\'aside-list-item\'>'

        if (true) {
          const name = 'data-lazy-src'
          result += `<a href='${array[i].url}' class='thumbnail'><img ${name}='${array[i].avatar}' alt='${array[i].nick}'></a>`
        }

        result += `<div class='content'>
        <a class='comment' href='${array[i].url}'>${array[i].content}</a>
        <div class='name'><span>${array[i].nick} / </span><time datetime="${array[i].date}">${btf.diffDate(array[i].date, true)}</time></div>
        </div></div>`
      }
    } else {
      result += '没有评论'
    }

    let $dom = document.querySelector('#card-newest-comments .aside-list')
    $dom.innerHTML= result
    window.lazyLoadInstance && window.lazyLoadInstance.update()
    window.pjax && window.pjax.refresh($dom)
  }

  const getComment = () => {
    const serverURL = 'https://cliyiuhj.lc-cn-n1-shared.com'

    var settings = {
      "method": "GET",
      "headers": {
        "X-LC-Id": 'ClIyIUhj1ue2rcRTsApYCR50-gzGzoHsz',
        "X-LC-Key": 'ATug9IScYQBHILhKWEqBHYxM',
        "Content-Type": "application/json"
      },
    }

    fetch(`${serverURL}/1.1/classes/Comment?limit=6&order=-createdAt`,settings)
      .then(response => response.json())
      .then(data => {
        const valineArray = data.results.map(function (e) {
          return {
            'avatar': getIcon(e.QQAvatar, e.mail),
            'content': changeContent(e.comment),
            'nick': e.nick,
            'url': e.url + '#' + e.objectId,
            'date': e.updatedAt,
          }
        })
        saveToLocal.set('valine-newest-comments', JSON.stringify(valineArray), 10/(60*24))
        generateHtml(valineArray)
      }).catch(e => {
        const $dom = document.querySelector('#card-newest-comments .aside-list')
        $dom.innerHTML= "无法获取评论，请确认相关配置是否正确"
      }) 
  }

  const newestCommentInit = () => {
    if (document.querySelector('#card-newest-comments .aside-list')) {
      const data = saveToLocal.get('valine-newest-comments')
      if (data) {
        generateHtml(JSON.parse(data))
      } else {
        getComment()
      }
    }
  }

  newestCommentInit()
  document.addEventListener('pjax:complete', newestCommentInit)
})</script><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script></div></body></html>